package com.example.myapplication

import android.content.Context
import android.content.res.Configuration
import com.alibaba.android.arouter.launcher.ARouter
import com.example.myapplication.data.realm.RealmUtils
import com.ftw.commons.BaseApplication
import com.ftw.commons.BuildConfig.BUGLY_APPID
import com.ftw.commons.crashreport.CrashHandler
import com.ftw.commons.language.LocalManageUtil
import com.tencent.bugly.crashreport.CrashReport
import kotlin.properties.Delegates


/**
 * 描    述：
 * 作    者：fantianwen
 * 时    间：2019/2/13  5:37 PM
 */
class App : BaseApplication() {


    companion object {
        var application: App by Delegates.notNull()
    }

    override fun getApplicationId(): String {
        return BuildConfig.APPLICATION_ID
    }

    override fun onCreate() {
        super.onCreate()
        application = this
        initARouter()
        RealmUtils.initRealm(application)
        initBuglyClient(application)
        LocalManageUtil.setApplicationLanguage(this)
    }


    override fun attachBaseContext(base: Context?) {
        //保存系统选择语言
        LocalManageUtil.saveSystemCurrentLanguage(base!!)
        super.attachBaseContext(LocalManageUtil.setLocal(base))

    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        super.onConfigurationChanged(newConfig)
        //保存系统选择语言
        LocalManageUtil.onConfigurationChanged(applicationContext)
    }


    /**
     * @name：初始化bugly收集
     * @desc: 初始化bugly收集
     * @input:
     * @return:
     **/
    private fun initBuglyClient(context: Context) {

        CrashHandler.getInstance().init(context)

        val strategy = CrashReport.UserStrategy(context)

        strategy.appChannel = "default"

        strategy.appVersion = BuildConfig.VERSION_NAME

        strategy.appPackageName = BuildConfig.APPLICATION_ID

        CrashReport.initCrashReport(
            context,
            BUGLY_APPID,
            BuildConfig.DEBUG, strategy
        )

    }


    /**
     * 初始化aroute
     */
    private fun initARouter() {
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog()   // 打印日志
            ARouter.openDebug()  // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this) // 尽可能早，推荐在Application中初始化
    }




}